package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.db.UserLocation;
import com.itheima.service.mongo.UserLocationService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zsk
 * @create 2022-03-20-19:27
 */
@DubboService
public class UserLocationServiceImpl implements UserLocationService {


    @Autowired
    private MongoTemplate mongoTemplate;

    //上报地理位置
    @Override
    public void saveLocation(Double longitude, Double latitude, String addrStr,Long userId) {
        //查询
        UserLocation userLocation = mongoTemplate.findOne(
                new Query(Criteria.where("userId").is(userId)), UserLocation.class);
        //判断
        if (userLocation == null){
            //新增用户
            userLocation = new UserLocation();
            userLocation.setUserId(userId);//当前用户id
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));//代表经纬度
            userLocation.setAddress(addrStr);//位置描述
            userLocation.setCreated(System.currentTimeMillis());//创建时间
            userLocation.setUpdated(System.currentTimeMillis());//更新时间
        }else {//代表存在用户，修改
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));// 地图坐标经纬度
            userLocation.setAddress(addrStr);//位置描述
            userLocation.setUpdated(System.currentTimeMillis());//更新时间
        }
        //调用mongo
        mongoTemplate.save(userLocation);

    }

    //搜附近
    @Override
    public List<Long> searchNearUser(Long userId, Long distance) {

        // 1.找圆心
        GeoJsonPoint location = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId)), UserLocation.class).getLocation();
        // 2.指定半径
        Distance dis = new Distance(distance / 1000, Metrics.KILOMETERS);
        // 3.画圆
        Circle circle = new Circle(location, dis);
        // 4.条件搜索
        Query query = new Query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocationList = mongoTemplate.find(query, UserLocation.class);
        // 5.遍历返回id
        List<Long> nearUserIdList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userLocationList)) {
            for (UserLocation userLocation : userLocationList) {
                nearUserIdList.add(userLocation.getUserId());
            }
        }
        return nearUserIdList;
    }
}
